#encoding = utf-8
#! /usr/sbin
#处理登陆请求，并返回token 给正常数据调用
from excelword.config import host,user,password,headers
import requests
#加上避免python警告看着难受
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import json
def login():
    login_url = "https://"+host+"/api/v1/namespaces/test-cli/login"
    login_data = {"name": user, "password": password}
    login_data = json.dumps(login_data)
    try:
        login_response = requests.post(url=login_url, headers=headers, data=login_data, verify=False)
        json_data = login_response.text   #其值为str
        if(json.loads(json_data)["code"]!= 0):
            print(str(json.loads(json_data)))
            return None
        else:
            # 由于json_data 的值为str，因此需要将其转为json文件再取其中的某项值
            token = str(json.loads(json_data)["data"]["loginResult"]["token"])
            headers["Cookie"] = "token="+token
            print("----login success---")
            return headers
        # str(json.loads(json_data)["message"]) == "message":
    except Exception as e:
         print("获取token产生异常，异常信息为:{error_message}".format(error_message=e))
         return None
         sys.exit(0)

if __name__ == '__main__':
    #测试入口
    login()